//
//  NSDate+sina.swift
//  时间比较
//
//  Created by hqhxu on 16/3/6.
//  Copyright © 2016年 hqhxu. All rights reserved.
//

import Foundation
/*
### 真机一定要指定区域
formatter.locale = NSLocale(localeIdentifier: "en")
*/
extension NSDate {
    //    Sun Mar 06 18:33:17 +0800 2016
    /// 通过字符串返回时间
    class func dateWithString(timeStr:String) -> NSDate? {
        
        let formatter = NSDateFormatter()
        
        formatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        
        formatter.locale = NSLocale(localeIdentifier: "EN")
        
        let date = formatter.dateFromString(timeStr)
        
        return date
    }
    
    /// 对象方法 date对象调用 然后和当前时间比较大小 返回不同的字符串
    func sinaDateDescrpition() -> String?{
        
        let calendar = NSCalendar.currentCalendar()
        
        if calendar.isDateInToday(self) {
            
            let date = Int(NSDate().timeIntervalSinceDate(self))
            
            if date < 60 {
                return "刚刚"
            } else if date < 60 * 60 {
                
                return"\(date / 60)分钟前"
                
            } else {
                
                return "\(date / 60 / 60 )小时前"
            }
        }
        
        var dfm = ""
        if calendar.isDateInYesterday(self) {
            
            dfm = "昨天 HH:mm"
            
        }else if calendar.compareDate(self, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedAscending {
            dfm = "yyyy-MM-dd HH:mm"
            
        }else if calendar.compareDate(self, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedSame {
            
            dfm = "MM-dd HH:mm"
        }
        
        let dateFormtter = NSDateFormatter()
        dateFormtter.dateFormat = dfm
        dateFormtter.locale = NSLocale(localeIdentifier: "EN")
        
        let dateStr = dateFormtter.stringFromDate(self)
        return dateStr
    }

}

